package com.base.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wnhuang
 * @Package com.base.utils
 * @date 2021-02-22 10:03
 */
public class CombinationUtil<T> {

    private List<List<T>> list = new ArrayList<>();

    private int target;

    private String fieldName;

    private List<T> candidates;

    public CombinationUtil(List<T> candidates, String fieldName, int target) {
        this.fieldName = fieldName;
        this.target = target;
        this.candidates = candidates;
    }

    public List<List<T>> combinationSum()  {
        dfs(0, new ArrayList<T>(), 0);
        return list;
    }

    public void dfs(int sum, List<T> combine, int idx)  {
        if (sum >= target) {
            list.add(combine);
        }
        if (idx >= candidates.size()) {
            return;
        }
        for (int i = idx; i < candidates.size(); i++) {
            ArrayList<T> list1 = new ArrayList<>(combine);
            list1.add(candidates.get(i));
            dfs(sum + (Integer) ReflectionUtils.getFieldValueByName(fieldName,candidates.get(i)), list1, i + 1);
        }
    }


}
